import * as React from 'react';
import { Callout } from 'office-ui-fabric-react/lib/Callout';
import { Link } from 'office-ui-fabric-react/lib/Link';
import { createRef } from 'office-ui-fabric-react/lib/Utilities';
import { getTheme, FontWeights, mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
import { SearchBox, Label, TextField, PrimaryButton } from 'office-ui-fabric-react';
import classnames from 'classnames'
import './index.less'
import Tag from '../../components/tag';
import store from '../../utils/localStorage';

const defaultDorpDown = [
  {
    "que": "近五年共享单车趋势统计"
  },
  {
    "que": "ofo的关系图"
  },
  {
    "que": "ofo和滴滴的关系"
  },
  {
    "que": "ofo融资事件"
  },
  {
    "que": "来电科技"
  },
  {
    "que": "来电科技融资事件"
  }
]


export interface Props {
  initValue?: any
  value?: any
  options?: any[] // 下拉option
  placeholder?: any
  onChange?: any
  onSearch?: any
  onAdvanceSearch?: any
}
export interface State {
  isDropDownVisible?: boolean;
  searchHistory: any[]
}

// Example code
export default class SearchAutoComplete extends React.Component<Props, State> {
  private _menuButtonElement = createRef<HTMLElement>();

  public constructor(props: Props) {
    super(props);

    this.state = {
      isDropDownVisible: false,
      searchHistory: []
    };
  }

  componentDidMount() {
    const searchHistory = store.getItem('searchHistory') || []
    this.setState({
      searchHistory
    })
  }
  componentWillUnmount() {
    const { searchHistory } = this.state
    store.setItem('searchHistory', searchHistory)
  }

  store = (value) => {
    if (!value) {
      return
    }
    const { searchHistory } = this.state
    if (searchHistory.indexOf(value) > -1) {
      return
    }
    if (searchHistory.length === 10) {
      searchHistory.unshift(value)
      searchHistory.pop()
    } else {
      searchHistory.push(value)
    }
    this.setState({
      searchHistory
    })
  }

  clearHistory = () => {
    this.setState({
      searchHistory: []
    })
  }

  handleClickOutside = (e) => {
    console.info('外部')
    this.hide()
    return
  }

  private handleChange = (value): void => {
    this.props.onChange(value)
    this.show()
  };
  private handleSearch = (value, e?: any): void => {
    console.info('搜索')
    this.hide()
    this.props.onSearch(value.replace(/(^\s*)|(\s*$)/g, ""))
    this.store(value)
  };

  show = (e?: any) => {
    console.info('显示')
    this.stopEvent(e)
    this.setState({
      isDropDownVisible: true
    })
    document.addEventListener('click', this.handleClickOutside);
    return
  }
  hide = () => {
    this.setState({
      isDropDownVisible: false
    })
    document.removeEventListener('click', this.handleClickOutside);
  }

  stopEvent(e) { //阻止冒泡事件
    if (e && e.stopPropagation) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    } else if (window.event) {
      // this code is for IE
      window.event.cancelBubble = true;
    }
  }

  public render(): JSX.Element {
    const { isDropDownVisible, searchHistory } = this.state;
    const { value, options, onSearch, onChange, children, ...restProps } = this.props

    // const { value, onSearch, onChange, searchList, recentData } = this.props

    // const searchList = [1, 2]

    return (
      <div className="search-box-wrap">
        <div className="search-box" onClick={this.show}>
          <SearchBox
            placeholder="搜索知识助手内容"
            value={value}
            onSearch={this.handleSearch}
            onChange={this.handleChange}
            {...restProps}
          />
          {children}
        </div>
        {
          isDropDownVisible && (
            <div className="search-down-wrap">
              <div className={classnames('search-list', { 'hide': !options.length })}>
                {
                  options.map(
                    (item, index) => <p key={index} role="button" className="dropdown-item" onClick={(e) => this.handleSearch(item.que, e)}>{item.que}</p>
                  )
                }
              </div>
              <div className="search-history">
                <div className="title">
                  <span className="left">
                    <i className="ms-Icon ms-Icon--History" aria-hidden="true"></i>
                    &nbsp;
                    最近搜索
                  </span>
                  <div className="pull-right">
                    <span className="pointer" onClick={this.clearHistory}>清空历史</span>
                  </div>
                </div>
                <div className="content">
                  {
                    searchHistory.map(
                      (item, index) => <Tag key={index} className="dropdown-item" onClick={(e) => this.handleSearch(item)} title={item} />
                    )
                  }
                </div>
              </div>
            </div>
          )
        }

      </div>
    );
  }

}
